<!-- 部门下有人员的组织结构 -->

<script setup>
import { toRefs, ref, onMounted, nextTick, watch } from 'vue';
import { ElDialog, ElTree, ElButton } from 'element-plus';
import { UNIQUE } from './common-helper';

const props = defineProps({
  deptDialogShow: Boolean,
  btnLoading: Boolean,
  userInfoArr: Array,
  isOnly: {
    type: Number,
    default: 1, // 0-代表单选, 1-代表多选
  },
});
const { deptDialogShow, userInfoArr, isOnly } = toRefs(props);
const emit = defineEmits(['closeDeptDialog', 'handleDeptInfo']);
const treeRef = ref();
const checkedArray = ref([]);

const checkedId = ref('');

const checkedNodes = ref([]); //选中的数据
const treeData = ref([]);
const checkedState = ref(false);

const defaultProps = {
  children: 'children',
  label: 'label',
  id: 'id',
  disabled: 'disabled',
};

onMounted(() => {
  groupByDeptApi();
});

watch(
  deptDialogShow,
  (val) => {
    if (val) {
      if (userInfoArr.value.length) {
        checkedArray.value = userInfoArr.value?.map((item) => {
          return item.id;
        });
      }
    }
  },
  { deep: true },
);

const closeDeptDialog = () => {
  emit('closeDeptDialog');
};

/*
 *@description: 查询部门职位树型
 */
const groupByDeptApi = () => {
  const data = [
    {
      deptId: '47091773642629120',
      deptName: '林业站',
      users: [
        {
          userId: '82637681439465472',
          username: '测试c',
        },
        {
          userId: '50746350803058688',
          username: '菲菲',
        },
        {
          userId: '50746408495710208',
          username: '菲',
        },
        {
          userId: '52952154230702080',
          username: '菲F',
        },
        {
          userId: '50746458294681600',
          username: '吴磊',
        },
        {
          userId: '56183600739143680',
          username: '杨二',
        },
        {
          userId: '56182170913492992',
          username: '杨一',
        },
        {
          userId: '46775008576356352',
          username: 'admin',
        },
      ],
    },
    {
      deptId: '47139956221530112',
      deptName: '东海道子管护站',
      users: [
        {
          userId: '59369954033778688',
          username: '陈七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七',
        },
        {
          userId: '52952154230702080',
          username: '菲F',
        },
        {
          userId: '46775008576356352',
          username: 'admin',
        },
      ],
    },
    {
      deptId: '47140049163112448',
      deptName: '北家海子管护站',
      users: [
        {
          userId: '52952154230702080',
          username: '菲F',
        },
        {
          userId: '58760563798441984',
          username: '测试',
        },
      ],
    },
    {
      deptId: '47140142771589120',
      deptName: '三滩水管护站',
      users: [
        {
          userId: '52952154230702080',
          username: '菲F',
        },
        {
          userId: '46775008576356352',
          username: 'admin',
        },
      ],
    },
    {
      deptId: '47140204029399040',
      deptName: '凤凰台管护站',
      users: [],
    },
    {
      deptId: '47140277383581696',
      deptName: '鱼儿沟管护站',
      users: [
        {
          userId: '51050745675542528',
          username: '魏立',
        },
      ],
    },
    {
      deptId: '52219207487758336',
      deptName: '图灵普惠',
      users: [
        {
          userId: '58763688303263744',
          username: '热辐射的热辐射的热辐射的热辐射的热辐射的热辐射的热辐射的热辐射的热辐射的热辐射的',
        },
        {
          userId: '50759486071341056',
          username: 'Diper',
        },
        {
          userId: '59854251874197504',
          username: '丽洁夫',
        },
        {
          userId: '79372865958502400',
          username: '测试B',
        },
        {
          userId: '81845273365766144',
          username: '李文勤',
        },
        {
          userId: '73958745557893120',
          username: '杨A',
        },
        {
          userId: '82640576461332480',
          username: '测试d',
        },
        {
          userId: '84851735847473152',
          username: '测试e',
        },
        {
          userId: '50746350803058688',
          username: '菲菲',
        },
        {
          userId: '53577011515535360',
          username: '杨哲勿删',
        },
        {
          userId: '59083128563757056',
          username: '王仁浩',
        },
        {
          userId: '52952154230702080',
          username: '菲F',
        },
        {
          userId: '59082515557838848',
          username: '测试',
        },
        {
          userId: '46775008576356352',
          username: 'admin',
        },
      ],
    },
    {
      deptId: '52511870262919168',
      deptName: '西安市三图科技有限',
      users: [],
    },
    {
      deptId: '52513707154161664',
      deptName: '积木科技',
      users: [
        {
          userId: '50746350803058688',
          username: '菲菲',
        },
        {
          userId: '52952154230702080',
          username: '菲F',
        },
        {
          userId: '46775008576356352',
          username: 'admin',
        },
      ],
    },
    {
      deptId: '52564990628151296',
      deptName: '数字孪生',
      users: [],
    },
    {
      deptId: '54791447039328256',
      deptName: '测试部门',
      users: [],
    },
    {
      deptId: '55102663615983616',
      deptName: '三图信息技术',
      users: [],
    },
    {
      deptId: '55105873600720896',
      deptName: '监测部门',
      users: [],
    },
    {
      deptId: '56110308183388160',
      deptName: '御道口乡管护站',
      users: [],
    },
    {
      deptId: '56235666618662912',
      deptName: '研发',
      users: [],
    },
    {
      deptId: '73975048108703744',
      deptName: '测试1部',
      users: [],
    },
  ];

  const tree = getTreeData(data);

  treeData.value = tree;
};

//  树形结构处理
const getTreeData = (data) => {
  for (var i = 0; i < data.length; i++) {
    let item = data[i];

    // if (item?.users?.length) {
    //   item.users = item.users.filter((items) => items.userId !== userInfo.value.id);
    // }

    item['id'] = item?.deptId ?? item.userId;
    item['label'] = item?.deptName ?? item.username;
    item['children'] = item?.users ?? [];

    if ('users' in item && !item?.users?.length) {
      item['disabled'] = true;
    }

    if (item?.users?.length) {
      getTreeData(item.users);
    }
  }

  return data;
};

// 操作
const handleCheckChange = (nodeObj, SelectedObj) => {
  const parentChildNodes =
    treeRef.value.getNode(nodeObj).parent.data.children ?? treeRef.value.getNode(nodeObj).parent.data[0].children; // 获取选择的数据

  if (isOnly.value == 1) {
    /*_______________多选项 最后选中值事件________________*/
    SelectedObj.checkedKeys.push(-1);
    SelectedObj.checkedKeys.sort((old, New) => {
      return old - New;
    });
  } else {
    /*_______________单选项 最后选中值数组对象事件________________*/
    parentChildNodes.forEach((ele) => {
      SelectedObj.checkedNodes.forEach((checked, i) => {
        if (ele.value == checked.value) {
          SelectedObj.checkedNodes.splice(i, 1);
          SelectedObj.checkedNodes.push(nodeObj);
        }

        SelectedObj.checkedNodes = UNIQUE(SelectedObj.checkedNodes); // 去重
      });
    });
  }

  SelectedObj.checkedKeys.forEach((value) => {
    parentChildNodes.forEach((ele) => {
      if (value == ele.value) {
        let index = SelectedObj.checkedKeys.indexOf(value);

        SelectedObj.checkedKeys.splice(index, 1);
      }

      SelectedObj.checkedKeys.push(nodeObj.value);
      SelectedObj.checkedKeys = [...new Set(SelectedObj.checkedKeys)]; // 去重
      SelectedObj.checkedKeys.sort((old, New) => {
        return old - New;
      });
    });
  });

  nextTick(() => {
    treeRef.value.setChecked(SelectedObj.checkedKeys, true); // 选中树
  });

  if (isOnly.value === 1) {
    checkedNodes.value = SelectedObj.checkedNodes.filter((item) => {
      if (item.userId) {
        return item;
      }
    });
  } else {
    checkedNodes.value = SelectedObj.checkedNodes.filter((item) => {
      if (item.userId) {
        return item;
      }
    }); // 这是选中的节点数据
  }
};

const handleCheckChangeOne = (data, checked) => {
  checkedState.value = checked;

  if (isOnly.value !== 1) {
    if (checked) {
      checkedId.value = data.id;
      treeRef.value.setCheckedKeys([data.id]);
    } else {
      if (checkedId.value === data.id) {
        treeRef.value.setChecked([data.id], false);
      }
    }
  }
};

const handleSaveUserInfo = () => {
  emit('handleDeptInfo', checkedNodes.value);
};
</script>
<template>
  <div class="position-dialog">
    <ElDialog
      :title="'选择人员'"
      :model-value="deptDialogShow"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
      :align-center="true"
      @close="closeDeptDialog()"
    >
      <main>
        <div class="tree_top">
          <p>人员组织结构</p>
        </div>
        <div class="tree_content">
          <ElTree
            ref="treeRef"
            show-checkbox
            node-key="id"
            :data="treeData"
            :props="defaultProps"
            default-expand-all
            :default-checked-keys="checkedArray"
            @check="handleCheckChange"
            @check-change="handleCheckChangeOne"
          >
          </ElTree>
        </div>

        <div class="dialog-footer">
          <ElButton @click="closeDeptDialog()">取消</ElButton>
          <ElButton type="primary" :loading="btnLoading" @click="handleSaveUserInfo()">确定</ElButton>
        </div>
      </main>
    </ElDialog>
  </div>
</template>

<style scoped lang="scss">
.position-dialog {
  :deep(.el-dialog) {
    width: 780px;
    border-radius: 10px;
  }
  :deep(.el-dialog__header) {
    color: #565656;
    font-weight: 700;
    font-size: 16px;
    border-bottom: 1px solid #f8f8f8;
  }
  :deep(.el-dialog__title) {
    font-size: 16px;
  }
  :deep(.el-dialog__headerbtn) {
    top: -5px !important;
    font-size: 20px !important;
  }
}
main {
  box-sizing: border-box;
  width: 100%;
  height: 610px;

  .tree_top {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  p {
    color: #666;
    font-size: 18px;
  }
  .tree_content {
    width: 100%;

    height: 510px;
    margin-top: 16px;
    padding: 18px 41px;
    overflow: auto;
    border: 1px solid #efefef;
    :deep(.el-tree-node__content) {
      margin-bottom: 14px;
      color: #333333;
      font-size: 16px;
    }
    :deep(.el-tree .el-tree-node .is-leaf + .el-checkbox .el-checkbox__inner) {
      display: inline-block;
    }
    :deep(.el-tree .el-tree-node .el-checkbox .el-checkbox__inner) {
      display: none;
    }
  }

  .dialog-footer {
    margin-top: 26px;
    text-align: right;
    :deep(.el-button) {
      width: 80px;
      height: 36px;
      color: #377bf0;
      border-color: #377bf0;
      border-radius: 4px;
    }
    :deep(.el-button--primary) {
      color: #ffffff;
    }
  }
  :deep(.el-button:focus, .el-button:hover) {
    color: #377bf0;
    background: #ffffff;
    border-color: #377bf0;
  }

  :deep(.el-checkbox__input.is-disabled .el-checkbox__inner) {
    background-color: #a9a9a9;
  }
}
</style>
